﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

namespace Heyu.Utility
{
    /// <summary>
    /// 加密
    /// </summary>
    public class EncryptUtility
    {
        static string _KEY = "D9)3!|WU";  //密钥  
        static byte[] byIV = { 68, 5, 41, 51, 33, 124, 87, 85 };

        /// <summary>
        /// 加密（MD5）
        /// </summary>
        /// <param name="password"></param>
        /// <param name="passwordFormat"></param>
        /// <returns></returns>
        public static string Encrypt(string password, string passwordFormat = "md5")
        {
            if (!string.IsNullOrEmpty(password))
            {
                return FormsAuthentication.HashPasswordForStoringInConfigFile(password, passwordFormat);
            }
            else
            {
                return "";
            }
        }

        /// <summary>  
        /// Des加密  
        /// </summary>  
        /// <param name="data"></param>  
        /// <returns></returns>  
        public static string EncryptOfDes(string data)
        {

            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();

            string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
            return strRet;
        }

        /// <summary>  
        /// Des解密  
        /// </summary>  
        /// <param name="data"></param>  
        /// <returns></returns>  
        public static string DecryptOfDes(string data)
        {

            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);

            data.Replace("_%_", "/");
            data.Replace("-%-", "#");
            byte[] byEnc = Convert.FromBase64String(data);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }


    }
}
